package com.victor.register;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by DJJ on 2019/3/12.
 */
//rpc试用zk 的注册中心
public class RpcRegistry {
    public static final Logger LOGGER= LoggerFactory.getLogger(RpcRegistry.class);
    //zkService 的地址信息
    private String registryAddress;

    public String getRegistryAddress() {
        return registryAddress;
    }

    public void setRegistryAddress(String registryAddress) {
        this.registryAddress = registryAddress;
    }
    //当有提供有参构造时,也提供无参构造
    public RpcRegistry() {
    }

    public RpcRegistry(String registryAddress) {
        this.registryAddress = registryAddress;
    }

    private ZooKeeper zooKeeper;

    public void createNode(String serverAddress) throws Exception {
        zooKeeper= new ZooKeeper(registryAddress, Constant.SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
        if (zooKeeper!=null){
            try {
                Stat exists = zooKeeper.exists(Constant.REGISTRY_PATH, false);
                if (exists==null){//第一个注册还没有存在节点,
                    //创建一个持久节点,当做root
                    zooKeeper.create(Constant.REGISTRY_PATH,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
                //创建临时节点,保存对应的信息,在这里保存服务端的地址信息
                zooKeeper.create(Constant.DATA_PATH,serverAddress.getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
            } catch (Exception e) {
                LOGGER.error("注册失败:"+e.getMessage());
                e.printStackTrace();
            }
        }else {
            LOGGER.debug("zooKeeper connect is null");
        }
    }

    public static void main(String[] args) throws Exception {
        RpcRegistry rpcRegistry=new RpcRegistry("127.0.0.1:2181");
        rpcRegistry.createNode("djj");
        //让程序等待输入,程序一直处于运行状态
        System.in.read();
    }
}
